package cn.com.netedge.iot.frontend.comm.mq;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.MqConstants;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import cn.com.netedge.iot.frontend.comm.utils.JmsMsgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class UpMessageProducer {
    private static Logger logger = LoggerFactory.getLogger(UpMessageProducer.class);

    public void sendUpMessage(String deviceNumber, int deviceType, String message) {
        if (StringUtil.isEmpty(deviceNumber)) {
            logger.error("deviceNumber is empty");
            return;
        }
        String destination = MqConstants.QUEUE_UP_MESSAGE_NORMAL;
        //若终端有召读任务，消息放入高优先级队列
        if(isHavingTask(deviceNumber, deviceType)) {
            destination = MqConstants.QUEUE_UP_MESSAGE_EMERGENCY;
        }

        JmsMsgUtil.sendMessage(destination, message);
    }

    //任务采用队列（先进先出）
    private boolean isHavingTask(String deviceNumber, int deviceType) {
        String rtuTaskKey = CacheKeyConstants.KEY_DEVICE_TASK + deviceNumber + "_" + deviceType;
        long length = RedisUtil.llen(rtuTaskKey);
        if (length > 0) {
            return true;
        }
        return false;
    }
}
